import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';

import 'package:netease_cloud_music_api/netease_cloud_music_api.dart';
import 'package:image/image.dart' as pickerImage;
import 'package:image_picker/image_picker.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String? _platformVersion;
  String? filename;
  Image? image;
  pickerImage.Image? image2;
  final picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    // initPlatformState();
  }

  Future<void> initPlatformState(int phone, String password, BuildContext context) async {
    try {
      PlayerRequestResponse response = await NeteaseCloudMusicApi().cellphone(phone: phone, password: password);
      PlayerRequestResponse status = await NeteaseCloudMusicApi().status();
      print(status.body);
      setState(() {
        _platformVersion = response.body.toString();
      });
    } catch (e) {
      // print(e);
    }
  }

  Future _gaussianBlur() async {
    if (image2 != null) {
      try {
        pickerImage.Image gaussianBlur = pickerImage.gaussianBlur(image2!, 50);
        setState(() {
          image = Image.memory(pickerImage.encodePng(gaussianBlur) as Uint8List);
        });
      } catch (e) {
        print(e);
      }
    }
  }

  Future _getImageFromGallery(String data) async {
    try {
      final pickedFile = await (picker.getImage(source: data == 'gallery' ? ImageSource.gallery : ImageSource.camera) as FutureOr<PickedFile>);
      File file = File(pickedFile.path);
      String _fileName = file.path.split(file.parent.path + '/').last;
      pickerImage.Image _image = pickerImage.decodeNamedImage(file.readAsBytesSync(), _fileName)!;
      pickerImage.Image _image2 = pickerImage.drawString(_image, pickerImage.arial_14, 0, 0, '@zybbs', color: 0xFF000000);
      PlayerRequestResponse response = await NeteaseCloudMusicApi().playlistCoverUpload(
        fileName: _fileName,
        imageData: pickerImage.encodeJpg(_image2) as Uint8List,
        imgSize: _image.height.toString(),
        playlistId: 3143833470
      );
      setState(() {
        _platformVersion = response.body.toString();
      });
      setState(() {
        filename = _fileName;
        image2 = _image2;
        image = Image.memory(pickerImage.encodePng(_image2) as Uint8List);
      });
    } catch (e) {
      print(e);
      // print(e.response);
      // print(e.response.headers);
    }
  }

  _getData() async {
    try {
      PlayerRequestResponse response = await NeteaseCloudMusicApi().status();
      print(response.body.runtimeType);
      setState(() {
        _platformVersion = response.body.toString();
      });
    } catch (e) {
      print(e);
    }
  }

  _showCupertinoDialog(BuildContext context) {
    int? phone;
    String? password;
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text(
              '登录提示',
            ),
            content: SingleChildScrollView(
              child: Card(
                elevation: 0.0,
                color: Colors.transparent,
                child: Column(
                  children: <Widget>[
                    ConstrainedBox(
                      constraints: BoxConstraints(
                        maxHeight: 40,
                      ),
                      child: TextField(
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: '手机号码',
                          contentPadding: EdgeInsets.only(left: 10, top: 0),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                              color: Color(0xff9e51ff),
                            ), //这个不生效
                          ),
                          enabledBorder: OutlineInputBorder(
                            //未选中时候的颜色
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                              color: Color(0xff9e51ff),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            //选中时外边框颜色
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                              color: Color(0xff9e51ff),
                            ),
                          ),
                        ),
                        onChanged: (value) {
                          phone = int.parse(value);
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 20),
                      child: ConstrainedBox(
                        constraints: BoxConstraints(
                          maxHeight: 40,
                        ),
                        child: TextField(
                          obscureText: true,
                          decoration: InputDecoration(
                            hintText: '密码',
                            contentPadding: EdgeInsets.only(left: 10, top: 0),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0),
                              borderSide: BorderSide(
                                color: Color(0xff9e51ff),
                              ), //这个不生效
                            ),
                            enabledBorder: OutlineInputBorder(
                              //未选中时候的颜色
                              borderRadius: BorderRadius.circular(5.0),
                              borderSide: BorderSide(
                                color: Color(0xff9e51ff),
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              //选中时外边框颜色
                              borderRadius: BorderRadius.circular(5.0),
                              borderSide: BorderSide(
                                color: Color(0xff9e51ff),
                              ),
                            ),
                          ),
                          onChanged: (value) {
                            password = value;
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            actions: [
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('取消'),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  if (phone != null || password != null) {
                    initPlatformState(phone!, password!, context);
                    Navigator.pop(context);
                  }
                },
                child: Text('确定'),
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              RaisedButton(
                onPressed: () {
                  _showCupertinoDialog(context);
                },
                child: Text("登录"),
              ),
              RaisedButton(
                onPressed: () {
                  _getImageFromGallery('gallery');
                },
                child: Text("相册"),
              ),
              RaisedButton(
                onPressed: () {
                  _getImageFromGallery('camera');
                },
                child: Text("拍照"),
              ),
              RaisedButton(
                onPressed: () {
                  _gaussianBlur();
                },
                child: Text("图片模糊"),
              ),
              RaisedButton(
                onPressed: () {
                  _getData();
                },
                child: Text("数据获取"),
              ),
              _platformVersion != null
                  ? Text(
                      _platformVersion!,
                      style: TextStyle(fontSize: 25),
                    )
                  : image == null
                      ? Container()
                      : Image(
                          image: image!.image,
                          width: double.infinity,
                        )
            ],
          ),
        ),
      ),
    );
  }
}
